import { Component, ElementRef, Input, Output, OnInit, ViewChild, Injectable, EventEmitter } from '@angular/core';
import { ZQPaymentService } from "./zq-payment.service";
import { Util } from "../../../../common/util";
import * as _ from 'lodash';


/**
 * 新股更新下一处理状态
 */
@Component({
  selector: 'new-stock-zq-zq-payment',
  templateUrl: './zq-payment.component.html',
  styleUrls: ['./zq-payment.component.scss'],
  providers: [ZQPaymentService]
})
export class ZQPaymentComponent implements OnInit {

  // 1-上交所， 2-深交所 0-全部
  public options: string = "0";

  @Input()
  public parameter: any;

  public modalStatus: boolean;

  // 发布刷新事件
  @Output()
  public refreshData: EventEmitter<any> = new EventEmitter<any>();

  @ViewChild("modal")
  public modal: ElementRef;

  constructor(public zQPaymentService: ZQPaymentService) {

  }

  ngOnInit() {
  }

  openModal(): void {
    this.modalStatus = true;
    Util.$(this.modal.nativeElement).modal('show');
  }

  public closeModal(): void {
    this.modalStatus = false;
    Util.$(this.modal.nativeElement).modal('hide');
  }

  public toggleModal(): void {
    this.modalStatus = !this.modalStatus;
    Util.$(this.modal.nativeElement).modal('toggle');
  }

  /**
   * [transferMoneyWithMarket 根据交易市场对当天交款的数据发起缴款]
   */
  transferMoneyWithMarket() {
    var that = this;
    if (that.options === "0") {
      that.options = "";
    }
    // 当天日期
    const date = window['moment'](new Date()).format('YYYYMMDD');
    that.transferMoney(null, date, that.options);
  }

  /**
   * [transferMoney 缴款确认]
   * @param {[type]} needTMObj   [需要确认的数组, 没有传null]
   * @param {[type]} date   [缴款日,没有传null]
   * @param {[type]} market [1-上交所，2深交所，空-上交所和深交所, 没有传null]
   */
  transferMoney(needTMObj, date, vcMarket) {
    const that = this;
    // 1.编辑提示信息
    let message = "";
    if (date != null) {
      message = "您未选择执行数据，默认选择当天交易数据生成划款指令，确定要生成划款指令吗？";
    } else {
      message = `您选择了${needTMObj.length}行数据，确定要生成划款指令？`;
    }
    // 2.提示用户是否进一步操作
    window["swal"]({
      title: "",
      text: message,
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      closeOnCancel: true,
      showLoaderOnConfirm: true
    },
      function (isConfirm) {
        if (isConfirm) {
          const opt = {
            check:true,
            recover:false
          }
          if (date) { // 将今天的数据都生成划款指令
            const param = {
              lJkDate: date,
              vcMarket: vcMarket,
              pmkyList:[]
            };
            that.zQPaymentService.transferMoney(param,opt).subscribe(result => {
              // 如果没有可生成划款指令的数据
              if(result.data.matchNull){
                window["swal"]("提示", result.data.matchNull, "warning");
              }
              // if (result) {
              //   window["swal"]("提示", "缴款确认成功!", "success");
              //   // 刷新列表
              //   that.closeModal();
              //   that.sendRefreshAction("true");
              // }
            });
          } else if (needTMObj) { // 只将勾选的数据生成划款指令
            const param = {
              pmkyList:[]
            }
            needTMObj.forEach(item => {
              param.pmkyList.push(item.pmkyNum)
            });
            that.zQPaymentService.transferMoney(param,opt).subscribe(result => {
              // 如果重复下指令
              if (result.data.transferedFund) {
                window["swal"]({
                  title: "",
                  text: result.data.transferedFund,
                  type: "warning",
                  showCancelButton: true,
                  confirmButtonColor: "#DD6B55",
                  confirmButtonText: "确认",
                  cancelButtonText: "取消",
                  closeOnConfirm: false,
                  closeOnCancel: true,
                  showLoaderOnConfirm: true
                },
                  function (isConfirm) {
                    if (isConfirm) {
                      const opt = {
                        check:false,
                        recover:true
                      }
                      that.zQPaymentService.transferMoney(param,opt).subscribe(result => {
                        if(result.code===0){
                          window["swal"]("提示", "缴款确认成功!", "success");
                          // 刷新列表
                          that.closeModal();
                          that.sendRefreshAction("true"); 
                        }
                      })
                    }
                  });
              }
              // 如果没有可生成划款指令的数据
              if(result.data.matchNull){
                window["swal"]("提示", result.data.matchNull, "warning");
              }
            });
          }
        } else {
          // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
        }
      });
  }

  // 发送更新请求动作
  public sendRefreshAction(item) {
    this.refreshData.emit({
      item: Object.assign({}, item)
    });
  }
}
